package com.nightwalkbuddy.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.nightwalkbuddy.dto.User;
import com.nightwalkbuddy.dao.UserProviderLive;

/**
 * user service class to login user online or offline, fetch user from DB
 * 
 * @author - htisabel
 * 
 */
public class UserServiceLive implements IUserService {

	private static final String CLASSNAME = "UserServiceLive.java";
	private static final String LOGIN_PARAM = "login";
	private static final String LOGIN_METHOD = "post";
	private static final String UNAME_PARAM = "uName";
	private static final String UPASS_PARAM = "uPass";
	private static final String LOGIN_URL = "http://homepages.uc.edu/~liuhi/nightwalkSite/android.php";

	@Override
	public String login(String username, String password) throws Exception {
		String result = "";

		/**
		 * compose and send HTTP request, receive HTTP response can be modified
		 * to accommodate more returned values for later sprint AsyncTask class
		 * for UI activity threading
		 */
		class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {

			@Override
			protected String doInBackground(String... params) {

				String paramUsername = params[0];
				String paramPassword = params[1];

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(LOGIN_URL);
				BasicNameValuePair postBasicNameValuePair = new BasicNameValuePair(
						LOGIN_PARAM, LOGIN_METHOD);
				BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair(
						UNAME_PARAM, paramUsername);
				BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair(
						UPASS_PARAM, paramPassword);
				ArrayList<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
				nameValuePairList.add(postBasicNameValuePair);
				nameValuePairList.add(usernameBasicNameValuePair);
				nameValuePairList.add(passwordBasicNameValuePAir);

				try {
					UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
							nameValuePairList);
					httpPost.setEntity(urlEncodedFormEntity);

					try {
						HttpResponse httpResponse = httpClient
								.execute(httpPost);
						InputStream inputStream = httpResponse.getEntity()
								.getContent();
						InputStreamReader inputStreamReader = new InputStreamReader(
								inputStream);
						BufferedReader bufferedReader = new BufferedReader(
								inputStreamReader);
						StringBuilder stringBuilder = new StringBuilder();
						String bufferedStrChunk = null;

						while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
							stringBuilder.append(bufferedStrChunk);
						}

						return stringBuilder.toString();

					} catch (ClientProtocolException cpe) {
						cpe.printStackTrace();
						Log.e(CLASSNAME, cpe.toString());
					} catch (IOException ioe) {
						ioe.printStackTrace();
						Log.e(CLASSNAME, ioe.toString());
					}

				} catch (UnsupportedEncodingException uee) {
					uee.printStackTrace();
					Log.e(CLASSNAME, uee.toString());
				}

				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
			}
		}

		SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
		sendPostReqAsyncTask.execute(username, password);
		result = sendPostReqAsyncTask.get();
		return result;
	}

	@Override
	public void save(Context context, String httpResponse) throws Exception {
		String delimiter = ",";
		String[] subStringHolder;
		User u = new User();
		UserProviderLive correctUser = new UserProviderLive(context);

		// split String using delimiter and set the user parameters
		subStringHolder = httpResponse.split(delimiter);
		u.setUsername(subStringHolder[0]);
		u.setPassword(subStringHolder[1]);
		u.setEmPhoneNr(subStringHolder[2]);
		u.setEmMsg(subStringHolder[3]);
		// save user
		correctUser.save(u);
	}

	@Override
	public User getUser(Context context, String username) throws Exception {

		UserProviderLive fetchUser = new UserProviderLive(context);

		return fetchUser.fetch(username);

	}

	@Override
	public boolean offlineLogin(Context context, String username,
			String password) throws Exception {
		boolean loginOK = false;
		User u = new User();
		try {
			u = getUser(context, username);
			String aName = u.getUsername();
			String aPass = u.getPassword();
			if (username.equals(aName) && password.equals(aPass)) {
				loginOK = true;
			}
		} catch (NullPointerException e) {
			Log.e(CLASSNAME, e.toString());
		} catch (Exception e1) {
			Log.e(CLASSNAME, e1.toString());
		}

		return loginOK;
	}

}
